package com.web.music.impl;

import java.util.ArrayList;
import java.util.List;

import com.web.music.interfaces.PersistenceHelper;
import com.web.music.interfaces.UserService;
import com.web.music.model.PersistentEntity;
import com.web.music.model.User;

public class UserServiceImpl implements UserService {
	
	private PersistenceHelper persistence;

	public List<User> findAll() {
		List<PersistentEntity> all = persistence.findAll(User.class);
		List<User> users = new ArrayList<User>();
		for (PersistentEntity e : all) {
			users.add((User) e);
		}
		return users;
	}

	public User getById(Long id) {
		return (User) persistence.getById(User.class, id);
	}

	public void save(User user) {
		persistence.save(user);
	}
	
	public User getByLoginPassword(String login, String password) {
		return persistence.findUserByLoginPassword(login, password);
	}
	
	public boolean existsAdminAccount(){
		boolean exists;
		try{
			User admin = persistence.findUserByLoginPassword("root", "root1");
			exists = admin!=null;
		}
		catch (javax.persistence.NoResultException e){
			exists = false;
		}
		return exists;
	}
	
	public boolean existsLogin(String login){
		boolean exists=false;
		List<User> users = findAll();
		for (User u : users) {
			if (login.equals(u.getUserName())) {
				exists= true;
			}
		}		
		return exists;
	}
	
	public PersistenceHelper getPersistence() {
		return persistence;
	}

	public void setPersistence(PersistenceHelper persistence) {
		this.persistence = persistence;
	}

}
